package com.samp.bblock.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MD5工具类
 */
public class Md5Util {
    private static final Logger LOGGER = LoggerFactory.getLogger(Md5Util.class);

    /**
     * 编码方式：UTF-8
     */
    private static final String CONTENT_ENCODING_UTF = "UTF-8";
    /**
     * 加密方式：MD5
     */
    private static final String ENCRYPTION_MODE_MD5 = "MD5";

    public static String secretKey16(String keyStr) {
        String md5Key = "";
        try {
            MessageDigest md = MessageDigest.getInstance(ENCRYPTION_MODE_MD5);
            byte[] digest = md.digest(keyStr.getBytes(CONTENT_ENCODING_UTF));
            md5Key = HexUtil.encodeHexStr(digest).substring(0, 16);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("加密异常,无此算法", e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("不支持的编码方式", e);
        }
        return md5Key;
    }

    public static String secretKey32(String keyStr) {
        String md5Key = "";
        try {
            MessageDigest md = MessageDigest.getInstance(ENCRYPTION_MODE_MD5);
            byte[] digest = md.digest(keyStr.getBytes(CONTENT_ENCODING_UTF));
            md5Key = HexUtil.encodeHexStr(digest).substring(0, 32);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("加密异常,无此算法", e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("不支持的编码方式", e);
        }
        return md5Key;
    }
}
